package cn.arikeky.pet.service.impl;

import cn.arikeky.basic.anno.PreAuthorize;
import cn.arikeky.basic.config.BussinessException;
import cn.arikeky.basic.domain.Point;
import cn.arikeky.basic.util.*;
import cn.arikeky.order.domain.OrderPetAcquisition;
import cn.arikeky.order.service.IOrderPetAcquisitionService;
import cn.arikeky.org.domain.Employee;
import cn.arikeky.org.domain.Shop;
import cn.arikeky.org.service.IEmployeeService;
import cn.arikeky.org.service.IShopService;
import cn.arikeky.pet.domain.SearchMasterMsg;
import cn.arikeky.pet.domain.SearchMasterMsgAuditLog;
import cn.arikeky.pet.dto.AcceptDto;
import cn.arikeky.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.arikeky.pet.mapper.SearchMasterMsgMapper;
import cn.arikeky.pet.query.SearchMasterMsgQuery;
import cn.arikeky.pet.service.ISearchMasterMsgService;
import cn.arikeky.basic.service.impl.BaseServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author arikeky
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private IShopService shopService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer messageTimeOut;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        // 保存数据
        searchMasterMsgMapper.add(searchMasterMsg);
        // 校验参数
        userInfoCheck(searchMasterMsg);
        // 百度AI 审核参数
        baiDuAICheck(searchMasterMsg);
        
        
        // 审核通过后寻找五十公里内最近的店铺挂牌，如果没有就进寻主池
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        List<Shop> shops = shopService.findAll();
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        if (shop != null) {
            searchMasterMsg.setShopId(shop.getId());
        }
        // 修改审核状态
        searchMasterMsg.setState(1);
        // 保存修改的所有数据
        searchMasterMsgMapper.update(searchMasterMsg);


        return AjaxResult.me().success();
    }

    @Override
    public PageList<SearchMasterMsg> selectSearchMasterMassageByParam(SearchMasterMsgQuery searchMasterMsg) {
        // 查询条数
        Integer totals = searchMasterMsgMapper.selectSearchMasterMassageByParamQueryCount(searchMasterMsg);
        if (null == totals || 0 ==totals){
            return new PageList<>(0,new ArrayList<>());
        }
        // 查询数据
        List<SearchMasterMsg> departments = searchMasterMsgMapper.selectSearchMasterMassageByParam(searchMasterMsg);

        //方到返回里面
        return new PageList<>(totals,departments);
    }

    @Override
    public void rejectById(Long msgId, Employee emp) {
        // 根据消息Id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        // 判断寻主消息是否为null   抛异常
        if (searchMasterMsg == null){
            throw new BussinessException("寻主消息为空，请重新操作");
        }
        // 讲shopid设置为null
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        // TODO 添加拒单日志
    }

    /**
     * 接单
     * @param acceptDto
     */
    @Override
    public void accept(AcceptDto acceptDto) {
        // 根据消息Id查询寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acceptDto.getMsgId());
        // 判断寻主消息是否为null   抛异常
        if (searchMasterMsg == null){
            throw new BussinessException("寻主消息为空，请重新操作");
        }
        // 安全问题加线程同步锁
        synchronized (searchMasterMsg.getId()){
            Employee employee = employeeService.findById(acceptDto.getHandler());
            if (employee == null) {
                throw new BussinessException("该员工不存在");
            }
            if (searchMasterMsg.getState() == 1 && searchMasterMsg.getShopId() == employee.getShopId()){
                // 修改寻主消息状态
                searchMasterMsg.setState(2);
                searchMasterMsgMapper.update(searchMasterMsg);
                // 生成订单
                initAcquisition(acceptDto, searchMasterMsg, employee);
            }
        }

    }

    private void initAcquisition(AcceptDto acceptDto, SearchMasterMsg searchMasterMsg, Employee employee) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(acceptDto.getHandler()));
        orderPetAcquisition.setDigest(acceptDto.getNote());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 3*24*60*60*1000));
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(searchMasterMsg.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionService.add(orderPetAcquisition);

        // 调用生产者方法
        sendDelayMsg(orderPetAcquisition.getOrderSn());
    }

    public void sendDelayMsg(String massage){
        rocketMQTemplate.syncSend("cancel_order", MessageBuilder.withPayload(massage).build(),messageTimeOut,4);
        System.out.println("生产者调用完成");
    }

    private void baiDuAICheck(SearchMasterMsg searchMasterMsg) {
        StringBuilder sbr = new StringBuilder();
        sbr.append(searchMasterMsg.getTitle())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getName())
                .append(searchMasterMsg.getCoatColor());
        if(!BaiduAuditUtils.TextCensor(sbr.toString())){
            // 设置日志数据
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setAuditTime(new Date());
            log.setState(0);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("百度AI审核不通过，填写信息违规，请到个人中心重新填写！");
            // 添加审核日志数据
            searchMasterMsgAuditLogMapper.add(log);
            throw new BussinessException("百度AI审核不通过，填写信息违规，请到个人中心重新填写！");
        }
    }

    private void userInfoCheck(SearchMasterMsg searchMasterMsg) {
        // 校验参数非空
        if (StringUtils.isBlank(searchMasterMsg.getName()) || StringUtils.isBlank(searchMasterMsg.getAddress())){
            // 设置日志数据
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setAuditTime(new Date());
            log.setState(0);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("填写不能为空，请到个人中心重新填写！");
            // 添加审核日志数据
            searchMasterMsgAuditLogMapper.add(log);
            throw new BussinessException("填写不能为空，请到个人中心重新填写！");
        }
    }
}
